//
//  Download.m
//  Example13-2
//
//  Created by 孙晓晔 on 2017/4/25.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "Download.h"
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonDigest.h>

#import "DownloadOperation.h"

@interface Download()<DownloadOperationDelegate>

@property(nonatomic, strong) NSFileManager *file;
@property(nonatomic, strong) NSString *dir; // 文件操作根目录
@end

@implementation Download

-(instancetype)initWithUrl:(NSArray*)arr {
    self = [super init];
    
    if (self) {
        _dict = [NSMutableDictionary dictionary];
        _urlArr = arr;
        
        NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        self.dir = [arr firstObject];
        self.file = [NSFileManager defaultManager];
        
        NSLog(@"文件存放目录 = %@", self.dir);
    }
    
    return self;
}

// 清除内存缓存
-(void)clear {
    self.dict = [NSMutableDictionary dictionary];
    NSLog(@"内存缓存已清空", nil);
}

// 启动下载
-(void)start:(NSInteger)count {
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    queue.maxConcurrentOperationCount = count;
    
    for (NSString *strURL in self.urlArr) {
        // NSLog(@"%@", str);
        
        if ([self.dict objectForKey:strURL]) {
            NSLog(@"内存缓存中已存在 = %@", strURL);
            continue;
        }
        
        if ([self didDownloadImage:strURL]) {
            NSLog(@"文件缓存中已存在 = %@", strURL);
            continue;
        }
        
        DownloadOperation *op1 = [[DownloadOperation alloc]initWithUrl:strURL];
        op1.delegate = self;
        
        [queue addOperation:op1];
    }
}

// 判断文件是否存在
-(BOOL)didDownloadImage:(NSString*)strURL {
    NSString *suffix = [strURL pathExtension];
    
    NSString *path = [self md5:strURL];
    
    NSString *strFile = [self.dir stringByAppendingFormat:@"/%@.%@", path, suffix];
    
//    NSLog(@"%@", strFile);
    
    if ([self.file fileExistsAtPath:strFile]) {
        
        NSData *data = [NSData dataWithContentsOfFile: strFile];
        
        [self.dict setValue:data forKey:strURL];
        
        if ([self.delegate respondsToSelector:@selector(didFinishDownload:)]) {
            [self.delegate didFinishDownload:_dict];
        }
        
        return true;
    }
    
    return false;
}

// 图片下载完成
-(void)didFinishDownload:(NSString*)strURL data:(NSData *)data {
    NSLog(@"正在下载文件 = %@", strURL);
    
    @synchronized (self) {
        
        [self writeFile:strURL data:data];
        
//        if ([_dict count] == [_urlArr count]) {
//            
//        }
    }
}

// 文件缓存
-(BOOL)writeFile:(NSString*)strURL data:(NSData *)data {
    
    [self.dict setValue:data forKey:strURL];
    
    if ([self.delegate respondsToSelector:@selector(didFinishDownload:)]) {
        [self.delegate didFinishDownload:_dict];
    }
    
    NSString *suffix = [strURL pathExtension];
    
    NSString *path = [self md5:strURL];
    
    NSString *strFile = [self.dir stringByAppendingFormat:@"/%@.%@", path, suffix];
    
    NSLog(@"正在保存文件 = %@", strFile);
    
    return [self.file createFileAtPath:strFile contents:data attributes:nil];
}

// md5编码
-(NSString *)md5:(NSString *)input {
    
    const char *cStr = [input UTF8String];
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return  output;
}

@end
